package obj;

import javax.media.j3d.Appearance;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.Matrix4f;

import outils.Constantes;
import outils.Materiaux;
import phyzik.solides.PhysiqueBalle;
import phyzik.solides.PhysiqueSolide;
import struct.Matrice4;

import com.sun.j3d.utils.geometry.Primitive;
import com.sun.j3d.utils.geometry.Sphere;

public class Balle implements Objet {

	protected BranchGroup balle;
	protected TransformGroup groupeBalle;
	protected Transform3D transf3D;
	public Appearance apparenceBalle;
	protected Sphere sphere;

	public PhysiqueSolide physique;

	public Matrix4f transformationPrecedente;
	public Matrix4f transformation;

	public float rho;

	public Balle() {
		rho = Constantes.RAYON_BALLE;

		physique = new PhysiqueBalle();

		balle = new BranchGroup();

		apparence();
		construire();

		balle.compile();
	}

	public BranchGroup getObjet() {
		return balle;
	}

	public PhysiqueSolide getPhysique() {
		return physique;
	}

	public void setPhysique(PhysiqueSolide ps) {
		this.physique = ps;
	}

	public void apparence() {
		apparenceBalle = new Appearance();
		apparenceBalle.setCapability(Appearance.ALLOW_MATERIAL_READ);
		apparenceBalle.setCapability(Appearance.ALLOW_MATERIAL_WRITE);
		//apparenceBalle.setMaterial(Materiaux.PLAS_BLEU);
		apparenceBalle.setMaterial(Materiaux.matAlea());
	}

	public void construire() {
		transf3D = new Transform3D();
		transf3D.set(physique.getTransformation());
		groupeBalle = new TransformGroup(transf3D);
		groupeBalle.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
		groupeBalle.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
		sphere = new Sphere(Constantes.RAYON_BALLE, Primitive.GENERATE_NORMALS
				| Primitive.GENERATE_TEXTURE_COORDS, apparenceBalle);
		groupeBalle.addChild(sphere);
		balle.addChild(groupeBalle);

		transformationPrecedente = new Matrix4f(Matrice4.identite());
		transformation = new Matrix4f(physique.getTransformation());
	}

	public void deplacer() {
		groupeBalle.getTransform(transf3D);
		Transform3D Mouvement = new Transform3D();

		transformationPrecedente.set(transformation);
		transformationPrecedente.invert();

		transformation.set(physique.getTransformation());

		Matrix4f temp = new Matrix4f(transformationPrecedente);
		temp.mul(transformation);

		Mouvement.set(temp);
		transf3D.mul(Mouvement);
		groupeBalle.setTransform(transf3D);
	}
}
